<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\ApiController;
use App\Models\Message;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class UserController extends ApiController
{
    public function getToken(Request $request)
    {
        $code = $request->input('code');
        $nickname = $request->input('nickname');
        $avatar = $request->input('avatar');

        if (empty($code)) {
            return $this->errorReturn('code 值找不到');
        }
        logger('miniProgram code -->' . $code);
        $miniProgram = \EasyWeChat::miniProgram();
        $data = $miniProgram->auth->session($code);
        logger('miniProgram data', $data);
        if (isset($data['errcode'])) {
            return $this->errorReturn('code已过期或不正确');
        }
        $openId = $data['openid'];
        $sessionKey = $data['session_key'];

        $user = User::where('openid', $openId)->first();
        if (empty($user->id)) {
            $user = new User([
                'openid' => $openId,
                'nickname' => $nickname,
                'avatarurl' => $avatar,
            ]);
            $user->save();
        } else {
            $user->nickname = $nickname;
            $user->avatarurl = $avatar;
            $user->openid = $openId;
            $user->save();
        }
        // 生成token, 保存session
        $token = md5($sessionKey ?: Str::random(32));
        // 保存user id 信息
        cache([ $token => $user->id ], 86400);
        $key = $user->id . '_login_session';
        cache([ $key => $sessionKey ], 86400);

        return $this->okReturn([
            'token' => $token,
        ]);

    }

    public function mobile(Request $request)
    {
        $userId = app('userId');
        if (!$userId) {
            return $this->errorReturn('请先登录');
        }
        $user = User::find($userId);
        if (empty($user->id)) {
            return $this->errorReturn('找不到用户');
        }
        $key = $user->id . '_login_session';
        $session_key = cache($key);
        if (!empty($session_key)) {
            $wechat = \EasyWeChat::miniProgram();
            $data = $wechat->encryptor->decryptData($session_key, $request->iv, $request->encryptedData);
            if (!empty($data['phoneNumber'])) {
                $user->mobile = $data['phoneNumber'];
                $user->save();
                return $this->okReturn([
                    'telephone' =>  $user->mobile,
                ]);
            }

            return $this->errorReturn('获取手机号码错误');
        }
    }

    public function getInfo(Request $request)
    {
        $userId = app('userId');
        if (!$userId) {
            return $this->errorReturn('请先登录');
        }
        $user = User::find($userId);
        if (empty($user->id)) {
            return $this->errorReturn('找不到用户');
        }
        $messageCount = Message::whereIn('receive_user_id', [$userId, 0])
            ->whereDoesntHave('userReadMessages', function($query) use ($userId) {
                $query->where('user_id', $userId);
            })
            ->count();
        return $this->okReturn([
            'no' => $user->id + 100000,
            'nickname' => $user->nickname,
            'avatarurl' => $user->avatarurl,
            'mobile' => $user->mobile,
            'balance' => $user->balance,
            'is_vip' => $user->is_vip,
            'messageCount' => $messageCount,
        ]);
    }
}
